﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Emerson.Storage.Core;
using System.Data.Objects;

namespace Emerson.Storage.ObjectContextInMemory
{
    /// <summary>
    /// Uses in memory storage for entities
    /// </summary>
    public class ObjectContextInMemory : IObjectContext
    {
        private readonly List<ObjectSetInMemory<object>> entities;

        public ObjectContextInMemory()
        {
            entities = new List<ObjectSetInMemory<object>>();
        }

        public void RegisterType(Type entityType)
        {
            bool isExisted = entities.Any(m => m.ElementType.Equals(entityType));
            if (isExisted)
                throw new ArgumentException("entityType already registered");

            var objectSet = new ObjectSetInMemory<object>();
            entities.Add(objectSet);
        }

        #region IObjectContext Members

        public void SaveChanges() { }

        public IObjectSet<T> CreateObjectSet<T>() where T : class
        {
            Type entityType = typeof(T);

            try
            {
                var objectSet = entities.Single(m => m.ElementType.Equals(entities));
                return (IObjectSet<T>)objectSet;
            }
            catch (InvalidOperationException)
            {
                throw new InvalidOperationException("Cannot find Entity of the specific type");
            }
        }

        #endregion
    }
}
